package com.shbaiche.bifenba.ui.video;

import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.shbaiche.bifenba.App;
import com.shbaiche.bifenba.R;
import com.shbaiche.bifenba.adapter.video.VideoDetailAdapter;
import com.shbaiche.bifenba.kit.AppKit;
import com.shbaiche.bifenba.model.base.TransMessage;
import com.shbaiche.bifenba.model.user.ShareMessage;
import com.shbaiche.bifenba.model.video.ArticleCollectMessage;
import com.shbaiche.bifenba.model.video.ArticleDetailMessage;
import com.shbaiche.bifenba.model.video.ArticleShareMessage;
import com.shbaiche.bifenba.model.video.ArticleVo;
import com.shbaiche.bifenba.model.video.DiscussAddMessage;
import com.shbaiche.bifenba.model.video.DiscussListMessage;
import com.shbaiche.bifenba.net.JsonCallback;
import com.shbaiche.bifenba.net.NetApi;
import com.shbaiche.bifenba.ui.base.BaseActivity;
import com.shbaiche.bifenba.ui.my.LoginActivity;
import com.shbaiche.bifenba.ui.my.SettingsActivity;
import com.shbaiche.bifenba.util.StringUtil;
import com.shbaiche.bifenba.util.ToastUtil;
import com.shbaiche.bifenba.view.CircularImage;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.droidlover.xdroidbase.router.Router;
import cn.droidlover.xstatecontroller.XStateController;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayer;
import fm.jiecao.jcvideoplayer_lib.JCVideoPlayerStandard;
import okhttp3.Call;


public class VideoDetailActivity extends BaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;

    @BindView(R.id.contentLayout)
    XStateController contentLayout;

    @BindView(R.id.video_list)
    ListView lv;

    @BindView(R.id.video_edit)
    EditText ed;
    @BindView(R.id.video_edit_tv)
    TextView edTv;

    AVLoadingIndicatorView aviLoadmore;

    TextView title;
    TextView name;
    TextView time;
    TextView follow;
    TextView guankan;
    CircularImage head;
    JCVideoPlayerStandard player;
    RelativeLayout pLayout;

    TextView xinwenTv;
    ImageView xinwenImg, xinwenImg1, xinwenImg2;
    LinearLayout xinwenLayout;

    View advLayout2;
    LinearLayout advLayout;
    TextView advTitle, advTitle2, advGuanzhu, advGuanzhu2;
    ImageView advImg, advImg2;


    VideoDetailAdapter mAdapter;

    private Long id;

    private String dType = "视频";

    private Dialog dg;

    private View loadMoreView, headView;

    private ImageView share;

    private int index = 0;


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
            return true;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void initData(Bundle savedInstanceState) {

        id = getIntent().getLongExtra("id", 0l);
        dType = getIntent().getStringExtra("type");
        dg = new Dialog(this);
        dg.setContentView(R.layout.view_loading);
        contentLayout.loadingView(View.inflate(this, R.layout.view_loading, null));
        contentLayout.showLoading();

        headView = getLayoutInflater().inflate(R.layout.activity_video_details_head, null);
        loadMoreView = getLayoutInflater().inflate(R.layout.view_loading_more, null);
        aviLoadmore = (AVLoadingIndicatorView) loadMoreView.findViewById(R.id.avi_loadmore);

        share = (ImageView) findViewById(R.id.video_share);

        title = (TextView) headView.findViewById(R.id.tv_video_title);
        name = (TextView) headView.findViewById(R.id.tv_video_name);
        time = (TextView) headView.findViewById(R.id.tv_video_time);
        follow = (TextView) headView.findViewById(R.id.tv_video_comment);
        guankan = (TextView) headView.findViewById(R.id.tv_video_guankan);
        head = (CircularImage) headView.findViewById(R.id.img_video_icon);
        player = (JCVideoPlayerStandard) headView.findViewById(R.id.player_list_video);
        pLayout = (RelativeLayout) headView.findViewById(R.id.player_list_video_layout);


        advLayout = (LinearLayout) headView.findViewById(R.id.adv_layout);
        advTitle = (TextView) headView.findViewById(R.id.adv_title);
        advGuanzhu = (TextView) headView.findViewById(R.id.adv_guanzhu);
        advImg = (ImageView) headView.findViewById(R.id.adv_img);
        advLayout2 = headView.findViewById(R.id.adv_center);
        advTitle2 = (TextView) headView.findViewById(R.id.adv_title2);
        advGuanzhu2 = (TextView) headView.findViewById(R.id.adv_guanzhu2);
        advImg2 = (ImageView) headView.findViewById(R.id.adv_img2);

        advLayout = (LinearLayout) headView.findViewById(R.id.adv_layout);
        advTitle = (TextView) headView.findViewById(R.id.adv_title);
        advGuanzhu = (TextView) headView.findViewById(R.id.adv_guanzhu);
        advImg = (ImageView) headView.findViewById(R.id.adv_img);

        xinwenImg = (ImageView) headView.findViewById(R.id.img_video_content_img);
        xinwenImg1 = (ImageView) headView.findViewById(R.id.img_video_content_img2);
        xinwenImg2 = (ImageView) headView.findViewById(R.id.img_video_content_img3);
        xinwenTv = (TextView) headView.findViewById(R.id.img_video_content_tv);
        xinwenLayout = (LinearLayout) headView.findViewById(R.id.img_video_content_layout);

        if ("资讯".equals(dType)) {
            xinwenLayout.setVisibility(View.VISIBLE);
            xinwenTv.setVisibility(View.VISIBLE);
            player.setVisibility(View.GONE);
            pLayout.setVisibility(View.GONE);
        } else {
            player.setVisibility(View.VISIBLE);
            pLayout.setVisibility(View.VISIBLE);
            xinwenLayout.setVisibility(View.GONE);
            xinwenTv.setVisibility(View.GONE);
        }

        loadMoreView.setVisibility(View.GONE);
        lv.addHeaderView(headView);
        lv.addFooterView(loadMoreView);
        lv.setFooterDividersEnabled(false);

        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ArticleShareMessage msg = new ArticleShareMessage();
                msg.setArticleId(id);
                NetApi.ArticleShare(msg, new JsonCallback<TransMessage>() {

                    @Override
                    public void onFail(Call call, Exception e, int id) {
                        dg.hide();
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.show("onFail" + e.getMessage());
                    }

                    @Override
                    public void onResponse(TransMessage response, int id) {
                        Gson gson = new Gson();
                        ArticleShareMessage msg = gson.fromJson(response.getMessage(), ArticleShareMessage.class);

                        if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {
                            AppKit.shareText(VideoDetailActivity.this, msg.getTitle() + msg.getUrl());
                        } else {
                        }
                    }
                });
            }
        });

        initSwipe();

        load();

        if (player != null) {
            player.release();
        }

        follow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                follow();
            }
        });

        edTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                addDis();
            }
        });
    }

    private void initSwipe() {

        //给listview设置一个滑动的监听
        lv.setOnScrollListener(new AbsListView.OnScrollListener() {
            int visibleLastIndex = 0;    //最后的可视项索引
            int visibleItemCount;        // 当前窗口可见项总数

            //当滑动状态发生改变的时候执行
            public void onScrollStateChanged(AbsListView view, int scrollState) {
                switch (scrollState) {
                    //当不滚动的时候
                    case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
                        int itemsLastIndex = mAdapter.getCount() - 1;    //数据集最后一项的索引
                        int lastIndex = itemsLastIndex + 1;                //加上底部的loadMoreView项
                        //判断是否是最底部
                        //if (view.getLastVisiblePosition() == (view.getCount()) - 1) { //或者
                        if (visibleLastIndex - 1 == lastIndex) {
                            if (index == -1) {
                                loadMoreView.setVisibility(View.GONE);
                            } else {
                                loadMoreView.setVisibility(View.VISIBLE);
                                index++;
                                disLoad();
                            }
                        }
                        break;
                }
            }

            //正在滑动的时候执行
            public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                this.visibleItemCount = visibleItemCount;
                visibleLastIndex = firstVisibleItem + visibleItemCount - 1;
            }
        });
    }

    private void follow() {

        if (App.getPassport() != null) {

            dg.show();

            ArticleCollectMessage msg = new ArticleCollectMessage();
            msg.setArticleId(id);
            msg.setPassport(App.getPassport());

            NetApi.ArticleCollect(msg, new JsonCallback<TransMessage>() {

                @Override
                public void onFail(Call call, Exception e, int id) {
                    ToastUtil.show("收藏失败");
                    dg.hide();
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    ToastUtil.show("onFail" + e.getMessage());
                    dg.hide();
                }

                @Override
                public void onResponse(TransMessage response, int id) {
                    dg.hide();
                    Gson gson = new Gson();
                    ArticleDetailMessage msg = gson.fromJson(response.getMessage(), ArticleDetailMessage.class);

                    if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {
                        ToastUtil.show("收藏成功!");
                        follow.setOnClickListener(null);
                    } else {
                        ToastUtil.show("收藏失败!");
                    }
                }
            });
        } else {
            ToastUtil.show("请先登录!");
            LoginActivity.launch(this);
        }
    }

    private void addDis() {

        String text = ed.getText().toString();
        if (TextUtils.isEmpty(text)) {
            ToastUtil.show("内容不能为空!");
            return;
        }

        if (App.getPassport() != null) {
            dg.show();

            DiscussAddMessage msg = new DiscussAddMessage();
            msg.setArticleId(id);
            msg.setPassport(App.getPassport());
            msg.setContent(text);

            NetApi.ArticleDiscussAdd(msg, new JsonCallback<TransMessage>() {

                @Override
                public void onFail(Call call, Exception e, int id) {
                    ToastUtil.show("发表失败");
                }

                @Override
                public void onError(Call call, Exception e, int id) {
                    ToastUtil.show("onFail" + e.getMessage());
                }

                @Override
                public void onResponse(TransMessage response, int id) {
                    Gson gson = new Gson();
                    ArticleDetailMessage msg = gson.fromJson(response.getMessage(), ArticleDetailMessage.class);

                    if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {
                        ToastUtil.show("发表成功!");
                        index = 0;
                        disLoad();
                        ed.setText("");
                        InputMethodManager imm = (InputMethodManager)
                                getSystemService(Activity.INPUT_METHOD_SERVICE);
                        if (ed != null) {
                            if (imm.isActive()) {
                                imm.hideSoftInputFromWindow(ed.getApplicationWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                            }
                        }
                    } else {
                        ToastUtil.show(msg.getMessage() + "");
                    }
                }
            });
        } else {
            ToastUtil.show("请先登录!");
            LoginActivity.launch(this);
        }
    }

    private void load() {
        ArticleDetailMessage msg = new ArticleDetailMessage();
        msg.setArticleId(id);

        NetApi.videoListDetail(msg, new JsonCallback<TransMessage>() {

            @Override
            public void onFail(Call call, Exception e, int id) {
                contentLayout.showContent();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                contentLayout.showContent();
                ToastUtil.show("onFail" + e.getMessage());
            }

            @Override
            public void onResponse(TransMessage response, int id) {

                contentLayout.showContent();

                Gson gson = new Gson();
                ArticleDetailMessage msg = gson.fromJson(response.getMessage(), ArticleDetailMessage.class);

                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {

                    ArticleVo vo = msg.getArticleVo();
                    title.setText(vo.getTitle() + "");
                    if (vo.getAuthor() != null) {
                        name.setText(vo.getAuthor().getName());
                        Glide.with(VideoDetailActivity.this).load(vo.getAuthor().getPhoto()).placeholder(R.drawable.ic_my_head).error(R.drawable.ic_my_head).into(head);
                    }
                    time.setText(vo.getPublishTime() + "");
                    long num = 0;
                    if (vo.getDiscussNum() != null)
                        num = vo.getDiscussNum();
                    guankan.setText(num + "次观看");
                    ArticleVo advVo = msg.getAdvert1();
                    if (advVo != null) {
                        advLayout.setVisibility(View.VISIBLE);
                        advTitle.setText(advVo.getTitle() + "");
                        long ping = advVo.getBrowseNum() == null ? 0 : advVo.getBrowseNum();
                        advGuanzhu.setText(ping + "球迷关注过");
                        if (advVo.getImgUrl() != null && advVo.getImgUrl().size() > 0) {
                            Glide.with(VideoDetailActivity.this).load(advVo.getImgUrl().get(0)).placeholder(R.drawable.defult).error(R.drawable.defult).into(advImg);
                        }
                    }

                    ArticleVo advVo2 = msg.getAdvert2();
                    if (advVo2 != null) {
                        advLayout2.setVisibility(View.VISIBLE);
                        advTitle2.setText(advVo2.getTitle() + "");
                        long ping = advVo2.getBrowseNum() == null ? 0 : advVo2.getBrowseNum();
                        advGuanzhu2.setText(ping + "球迷关注过");
                        if (advVo2.getImgUrl() != null && advVo2.getImgUrl().size() > 0) {
                            Glide.with(VideoDetailActivity.this).load(advVo2.getImgUrl().get(0)).placeholder(R.drawable.defult).error(R.drawable.defult).into(advImg2);
                        }
                    }

                    if ("资讯".equals(dType)) {
                        String con = TextUtils.isEmpty(vo.getContent()) ? "暂无数据" : vo.getContent();
                        xinwenTv.setText(con);
                        List<String> imList = vo.getImgUrl();
                        if (imList != null && imList.size() > 0) {
                            xinwenImg.setVisibility(View.GONE);
                            xinwenImg1.setVisibility(View.GONE);
                            xinwenImg2.setVisibility(View.GONE);
                            for (int i = 0; i < imList.size(); i++) {
                                switch (i) {
                                    case 0:
                                        xinwenImg.setVisibility(View.VISIBLE);
                                        Glide.with(VideoDetailActivity.this).load(imList.get(i)).into(xinwenImg);
                                        break;
                                    case 1:
                                        xinwenImg1.setVisibility(View.VISIBLE);
                                        Glide.with(VideoDetailActivity.this).load(imList.get(i)).into(xinwenImg1);
                                        break;
                                    case 2:
                                        xinwenImg2.setVisibility(View.VISIBLE);
                                        Glide.with(VideoDetailActivity.this).load(imList.get(i)).into(xinwenImg2);
                                        break;
                                }
                            }
                        }

                    } else {
                        player.setUp(vo.getVideoUrl(), JCVideoPlayer.SCREEN_LAYOUT_LIST, "");
                        Glide.with(VideoDetailActivity.this).load(vo.getThumbnail()).into(player.thumbImageView);
                    }
                    disLoad();
                } else {


                }

            }
        });
    }


    private void disLoad() {
        DiscussListMessage msg = new DiscussListMessage();
        msg.setArticleId(id);
        msg.setPageIndex(index);
        msg.setPageSize(10);

        NetApi.ArticleDiscussList(msg, new JsonCallback<TransMessage>() {

            @Override
            public void onFail(Call call, Exception e, int id) {
                dg.hide();
                contentLayout.showContent();
            }

            @Override
            public void onError(Call call, Exception e, int id) {
                dg.hide();
            }

            @Override
            public void onResponse(TransMessage response, int id) {

                dg.hide();
                Gson gson = new Gson();
                DiscussListMessage msg = gson.fromJson(response.getMessage(), DiscussListMessage.class);

                if (StringUtil.equalsIgnoreCase(TransMessage.SuccessCode, msg.getCode())) {
                    if (index == 0) {
                        mAdapter = new VideoDetailAdapter(VideoDetailActivity.this, msg.getVoList());
                        if (msg.getVoList() == null || msg.getVoList().size() < 10) {
                            index = -1;
                        }
                        lv.setAdapter(mAdapter);
                    } else {
                        mAdapter.addNewData(msg.getVoList());
                    }
                }
            }
        });
    }

    @Override
    public void setListener() {

    }

    public static void launch(Activity activity, Bundle b) {
        Router.newIntent(activity)
                .to(VideoDetailActivity.class)
                .data(b)
                .launch();
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_video_details;
    }

    @Override
    public void setToolbar() {
        initToolbar(toolbar, "详情");
    }

    @Override
    protected void onPause() {
        JCVideoPlayer.releaseAllVideos();
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        if (dg != null) {
            dg.dismiss();
            dg = null;
        }
        JCVideoPlayer.releaseAllVideos();
        super.onDestroy();
    }
}
